package top.lightHearted.bean;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.WebSocketSession;

/**
 * UserRegistry class
 *
 * @author gpf
 * @date 2018/04/16
 */
@Service("myUserRegistry")
public class UserRegistry {
    private ConcurrentMap<String, UserSession> usersByName = new ConcurrentHashMap<>();
    private ConcurrentMap<String, UserSession> usersBySessionId = new ConcurrentHashMap<>();

    public void register(UserSession userSession){
        usersByName.put(userSession.getName(), userSession);
        usersBySessionId.put(userSession.getSession().getId(), userSession);
    }

    public UserSession getByName(String name) {
        return usersByName.get(name);
    }

    public UserSession getBySession(WebSocketSession session) {
        return usersBySessionId.get(session.getId());
    }

    public boolean exists(String name) {
        return usersByName.keySet().contains(name);
    }

    public UserSession removeBySession(WebSocketSession session) {
        final UserSession user = getBySession(session);
        usersByName.remove(user.getName());
        usersBySessionId.remove(session.getId());
        return user;
    }

}
